<template>
  <van-config-provider
    :theme-vars="{
      // 标题栏
      navBarHeight: '50px',
      navBarBackground: '#202842',
      navBarTitleTextColor: 'white',
      navBarArrowSize: '20px',
      navBarIconColor: 'white',

      // Tabbar
      tabbarHeight: '50px',
      tabbarBackground: '#202842',
      tabbarItemTextColor: '#ffffff',
      tabbarItemActiveBackground: '#202842',
    }"
  >
    <!-- 路由 -->
    <div class="router" :class="tabbars.includes(route.path) ? 'active' : ''">
      <router-view v-slot="{ Component }" v-if="isInit">
        <keep-alive :include="['cache']">
          <component :is="Component"></component>
        </keep-alive>
      </router-view>
    </div>

    <!-- Tabbar -->
    <Base-Tabbar
      v-if="tabbars.includes(route.path) && isRenderTabbar"
    ></Base-Tabbar>
  </van-config-provider>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useStore } from '@/store/index'
import { showToast, showError } from 'js/utils'
import selects from 'js/selects'
import ContractContext from 'js/ContractContext'
import Web3 from 'web3'

const router = useRouter()
const route = useRoute()
const store = useStore()

const tabbars = ref(selects.tabbars.map((v) => v.url))
const isInit = ref(false) // 是否已初始化
const isRenderTabbar = ref(false)

onMounted(() => {
  // initWallet()

  // 登录
  if (location.hash === '#/') {
    router.replace('/user/login')
    renderView()
  } else {
    renderView()
  }

  setTimeout(() => {
    isRenderTabbar.value = true
  }, 50)
})

// 初始化钱包
async function initWallet() {
  const BINANCE_CHAIN_OBJECT = window.BinanceChain || window.ethereum

  if (typeof BINANCE_CHAIN_OBJECT === 'undefined') {
    isInit.value = false
    return showToast('请先安装Binance Wallet')
  }

  // 打开钱包
  BINANCE_CHAIN_OBJECT.enable()
  BINANCE_CHAIN_OBJECT.on('accountsChanged', onAccountChange)
  BINANCE_CHAIN_OBJECT.on('disconnect', onDisconnect)

  // 获取Web3实例
  window.web3 = new Web3(BINANCE_CHAIN_OBJECT)

  // 获取Usdt合约实例
  window.usdtContract = new ContractContext('usdt')

  // 获取User合约实例
  window.userContract = new ContractContext('user')

  // 获取Order合约实例
  window.orderContract = new ContractContext('order')

  // 获取用户钱包地址
  // window.fromAddress = await getFromAddress()
  window.fromAddress = '未接入'

  // 获取用户隐藏钱包地址
  window.fromAddressHide = fromAddress.replace(
    fromAddress.substring(10, 32),
    '*******'
  )

  // 获取用户上级地址
  // const parentAddress = await getParentAddress()

  // 判断用户是否已注册
  // if (parentAddress === '0x0000000000000000000000000000000000000000') {
  //   // 未注册
  //   router.replace(`/register?inviteId=${route.query.inviteId || ''}`)
  //   renderView()
  // } else {
  //   router.replace('/')
  //   renderView()
  // }

  // 登录
  if (location.hash === '#/') {
    router.replace('/user/login')
    renderView()
  } else {
    renderView()
  }
}

// 获取用户钱包地址
function getFromAddress(accounts) {
  return new Promise(async (resolve, reject) => {
    try {
      console.log('获取用户钱包地址')

      const [fromAddress] = accounts ? accounts : await web3.eth.getAccounts()

      if (typeof fromAddress === 'undefined') {
        isInit.value = false
        showToast('请先解锁Binance Wallet')
        reject()
      }

      const fromAddressLowwerCase = fromAddress.toLowerCase()
      console.log(`获取用户钱包地址成功：${fromAddressLowwerCase}`)
      resolve(fromAddressLowwerCase)
    } catch (err) {
      showError('获取用户钱包失败')
      console.error('获取用户钱包失败')
      console.error(err)
      reject(err)
    }
  })
}

// 获取用户上级地址
function getParentAddress() {
  return new Promise(async (resolve, reject) => {
    try {
      console.log('获取用户上级地址')
      const parentAddress = await userContract.context.methods
        .getParent(fromAddress)
        .call()
      console.log(`获取用户上级地址成功：${parentAddress}`)
      resolve(parentAddress)
    } catch (err) {
      showError('获取用户上级地址失败')
      console.error('获取用户上级地址失败')
      console.error(err)
      reject(err)
    }
  })
}

// 账户变化
function onAccountChange(accounts) {
  isInit.value = false
  showToast('账户发生变化，请刷新页面')
  getFromAddress(accounts)
}

// 断开连接
function onDisconnect() {
  isInit.value = false
  return showToast('已断开链接')
}

// 渲染View层
function renderView() {
  isInit.value = false
  setTimeout(() => {
    isInit.value = true
  }, 0)
}
</script>

<style lang="scss">
@import 'style/index.scss';

#app {
  max-width: var(--max-width);
  margin: 0 auto;

  .router {
    &.active {
      height: calc(100% - 50px);
    }
  }
}
</style>
